'use client';

import React, { useState, useEffect } from 'react';
import { Select, Spin } from 'antd';
import { request } from '@/utils/request';
import { API_ENDPOINTS } from '@/utils/constants';

// 定义产品接口
interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  unit: string;
  stockQuantity: number;
  imageUrl: string;
  categoryId: number;
  categoryName: string;
  status: string;
  origin: string;
  createdAt: string;
  updatedAt: string;
}

interface ProductSelectProps {
  value?: number;
  onChange?: (value: number) => void;
  placeholder?: string;
  style?: React.CSSProperties;
  disabled?: boolean;
}

const { Option } = Select;

const ProductSelect: React.FC<ProductSelectProps> = ({
  value,
  onChange,
  placeholder = '请选择产品',
  style,
  disabled = false,
}) => {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取产品列表
  const fetchProducts = async (keyword = '') => {
    setLoading(true);
    try {
      // 构造查询参数
      const params = new URLSearchParams({
        page: '0',
        size: '20',
      });
      
      if (keyword) {
        params.append('keyword', keyword);
      }

      const response = await request.get(`${API_ENDPOINTS.PRODUCTS.LIST}?${params.toString()}`);

      if (response.code === 200) {
        setProducts(response.data.content || []);
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProducts();
  }, []);

  // 搜索产品
  const handleSearch = (value: string) => {
    fetchProducts(value);
  };

  return (
    <Select
      showSearch
      value={value}
      onChange={onChange}
      placeholder={placeholder}
      style={style}
      disabled={disabled}
      loading={loading}
      onSearch={handleSearch}
      filterOption={false}
      notFoundContent={loading ? <Spin size="small" /> : null}
    >
      {products.map((product) => (
        <Option key={product.id} value={product.id}>
          {product.name}
        </Option>
      ))}
    </Select>
  );
};

export default ProductSelect;